<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Art extends BaseModel
{
    public $timestamps = false;

    protected $table = "article";

    protected $guarded = [];

    public function getOne($where, $fileds = '*')
    {
        return $this->multiSelect($fileds)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function ArtwithArttypeList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->with('article_category')->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->with('article_category')->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    public function article_category()
    {
        return $this->hasOne('App\Models\Arttype','id','position_id');
    }

    /**
     *插入数据
     */
    public function add($data)
    {
        return $this->_add($data);
    }


    /***
     * @param array $id
     * @param array $data
     * 更新数据
     */
    public function up($where, $data)
    {
        return $this->_updata($where, $data);
    }

    /**
     * @param $id
     * 删除数据
     */
    public function del($where)
    {
        return $this->_del($where);
    }

    /**
     *
     * 官方公告列表,带查询
     *
     */
    public function getNotesList($request)
    {

        $keywords = isset($request['keywords'])?trim($request['keywords']):'';

//        if (!empty($keywords)) {
//            if (is_numeric($request['keywords'])) {
//                $where['article_id'] = $request['keywords'];
//            } else {
//                $where['title'] = ['like', '%' . $request['keywords'] . '%'];
//            }
//        }
        $where['title'] = ['like', '%' . $keywords . '%'];
        $where['position_id'] = $request['article_category_id'];
        $rows = $this->ArtwithArttypeList($where,'*',['article_id'=>'desc'],5);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 3);
            return $rows;
        }

        return false;
    }

    /**
     *
     * 添加一条官方公告
     *
     */
    public function AddOneNote($request)
    {

        $title = isset($request['title'])?trim($request['title']):'';
        $sign = isset($request['sign'])?trim($request['sign']):'';
        $content = isset($request['content'])?trim($request['content']):'';


        if(!isset($title)||!isset($sign)||!isset($content)){
            $res['status'] = 0;
            $res['msg'] = '表单填写不完整!';
            return $res;
        }

        $data['title'] = $title;
        $data['sign'] = $sign;
        $data['content'] = $content;
        $data['position_id'] = $request['article_category_id'];
        $data['add_time'] = time();//添加时间

        $did = $this->add($data);
        if(!$did){
            $res['status'] = 0;
            $res['msg'] = '服务器繁忙,请稍后重试!';
            return $res;
        }

        $res['status'] = 1;
        $res['msg'] = '添加成功!';
        $res['url'] = $request['article_category_id'];
        return $res;


    }

    /**
     *  获取一条官方公告数据
     */
    public function getOneNote($request)
    {
        $article_id = isset($request['article_id'])?trim($request['article_id']):'';

        if(!empty($article_id)){
            $where['article_id'] = $article_id;
        }else{
            return '参数错误!';
        }

        $data = $this->getOne($where,'*')->toArray();
        return $data;
    }

    /**
     *  官方公告保存
     */
    public function saveOneNote($request)
    {

        $title = isset($request['title'])?trim($request['title']):'';
        $sign = isset($request['sign'])?trim($request['sign']):'';
        $article_id = isset($request['article_id'])?trim($request['article_id']):'';
        $content = isset($request['content'])?trim($request['content']):'';

        if(!isset($article_id)){
            $res['status'] = 0;
            $res['msg'] = '文章参数有误!';
            return $res;
        }

        if(!isset($title)||!isset($sign)||!isset($content)){
            $res['status'] = 0;
            $res['msg'] = '表单填写不完整!';
            return $res;
        }

        $data['title'] = $title;
        $data['sign'] = $sign;
        $data['content'] = $content;
        //$data['position_id'] = 1;

        $where['article_id'] = $article_id;
        $did = $this->up($where,$data);
        if(!$did){
            $res['status'] = 0;
            $res['msg'] = '服务器繁忙,请稍后重试!';
            return $res;
        }

        $res['status'] = 1;
        $res['msg'] = '修改成功!';
        $info = $this->getOne(['article_id'=>$article_id]);
        $res['url'] = $info['position_id'];
        return $res;


    }

    /**
     *
     * 删除一篇文章
     *
     */
    public function deleteOneArticle($request)
    {
        $article_id = trim($request['article_id']);
        if(!isset($article_id)){
            $data['status'] = 0;
            $data['msg'] = '传入参数有误！';
            return $data;
        }
        $where['article_id'] =$article_id;
        $did = $this->del($where);
        if($did){
            $data['status'] = 1;
            $data['msg'] = '删除成功！';
        }else{
            $data['status'] = 0;
            $data['msg'] = '删除失败！';
        }
        return $data;
    }


    /**
     * 团队信息列表
     */
    public function GroupArticleList($request)
    {

        $typemodel = new Arttype();
        $article_category_id = intval($request['article_category_id']);

        $info = $typemodel->getList(['parent_id'=>$article_category_id])->toArray();

        $arr[] = $article_category_id;       //查询id为7或者父级id为7的category表中的id,组成一个数组,使position_id等于其中元素
        foreach($info as $k=>$v){
            $arr[] = $v['id'];
        }

        $where['position_id'] = ['in',$arr];

        if (!empty($request['keywords'])) {

        $where['title'] = ['like', '%' . trim($request['keywords']) . '%'];

        }

        $rows = $this->ArtwithArttypeList($where,'*',['article_id'=>'desc'],4);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 3);
            return $rows;
        }
        return $rows;
    }



    /**
     * 帮助中心文章
     */
    public function getHelpIndex($request)
    {
        $article_category_id = isset($request['article_category_id'])?$request['article_category_id']:'';
        $article_category_id = intval($article_category_id);
        $arttype_model = new Arttype();
        $info = $arttype_model->getList(['parent_id'=>$article_category_id])->toArray();

        $arr[] = $article_category_id;       //查询id为6或者父级id为6的category表中的id,组成一个数组,使position_id等于其中元素
        foreach($info as $k=>$v){
            $arr[] = $v['id'];
        }

        $where['position_id'] = ['in',$arr];

        if (!empty($request['keywords'])) {

            $where['title'] = ['like', '%' . trim($request['keywords']) . '%'];

        }

        if (!empty($request['news_id'])) {

            $where['position_id'] = $request['news_id'];

        }

        $rows = $this->ArtwithArttypeList($where,'*',['article_id'=>'desc'],4);

        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 3);
            return $rows;
        }
    }



    /**
     *
     * 添加一条帮助中心文章
     *
     */
    public function AddOneHelp($request)
    {
        //dd($request);
        $title = isset($request['title'])?trim($request['title']):'';
        $sign = isset($request['sign'])?trim($request['sign']):'';
        $content = isset($request['content'])?trim($request['content']):'';


        if(!isset($title)||!isset($sign)||!isset($content)){
            $res['status'] = 0;
            $res['msg'] = '表单填写不完整!';
            return $res;
        }

        $data['title'] = $title;
        $data['sign'] = $sign;
        $data['content'] = $content;
        $data['position_id'] = $request['type_id'];
        $data['add_time'] = time();//添加时间

        $did = $this->add($data);
        if(!$did){
            $res['status'] = 0;
            $res['msg'] = '服务器繁忙,请稍后重试!';
            return $res;
        }

        $res['status'] = 1;
        $res['msg'] = '添加成功!';
        return $res;

    }

    /**
     *
     * 修改一条帮助中心文章
     *
     */
    public function SaveOneHelp($request){

        //dd($request);
        $title = isset($request['title'])?trim($request['title']):'';
        $sign = isset($request['sign'])?trim($request['sign']):'';
        $type_id = isset($request['type_id'])?trim($request['type_id']):'';
        $article_id = isset($request['article_id'])?trim($request['article_id']):'';

        if(empty($article_id)){
            $res['status'] = 0;
            $res['msg'] = '文章参数错误!';
            return $res;
        }

        if(!isset($title)||!isset($sign)||!isset($type_id)){
            $res['status'] = 0;
            $res['msg'] = '表单填写不完整!';
            return $res;
        }

        $data['title'] = $title;
        $data['sign'] = $sign;
        $data['position_id'] = $request['type_id'];
        $data['add_time'] = time();   //添加时间

        $did = $this->up(['article_id'=>$article_id],$data);
        if(!$did){
            $res['status'] = 0;
            $res['msg'] = '服务器繁忙,请稍后重试!';
            return $res;
        }

        $res['status'] = 1;
        $res['msg'] = '修改成功!';
        return $res;

    }


    /**
     * 帮助中心文章
     */
    public function getHelpIndex2($request)
    {
        $arttype_model =  new Arttype();
//       $article_category = $arttype_model->getList(['parent_id'=>6])->toArray(); //查找一级分类
//       foreach($article_category as $k=>$v)
//       {
//           //加入二级分类，以一级id为查询条件
//           //$where['parent_id'] = $v['id'];
//           $article_category[$k]['children']= $arttype_model->getList(['parent_id'=>$v['id']],'*',['id'=>'asc'],'')->toArray();
//       }

        $news_id = isset($request['news_id'])?trim($request['news_id']):'';
        $news_title = isset($request['news_title'])?trim($request['news_title']):'';

        if(!empty($news_id)){
            $where['id'] = $news_id;
        }
        //是否有帮助中心的类型查询
        if(!empty($news_title)){
            $where['news_title'] = $news_title;
        }

        $where['parent_id'] = 6;
        $rows = $arttype_model->ArttypewithArtList($where,'*',['id'=>'desc'],4);    //查询所有parent_id为6

        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 3);
            return $rows;
        }

    }

    /**
     * 获取文章列表
     * 官方公告,市场动态,团队信息
     */
    public function getArticleList($request)
    {

        $art_category_id = isset($request['art_category_id'])?trim($request['art_category_id']):'';
        $title = isset($request['title'])?trim($request['title']):'';
        $news_id = isset($request['news_id'])?trim($request['news_id']):'';

        if(!empty($art_category_id)){
            if($art_category_id==1){   //官方公告
                    $where['id'] = 1;
                if(!empty($title)){
                    $where['title'] = $title;
                }
                $model = new Arttype();
                $rows = $model->ArttypewithArtList($where,'*',['id'=>'desc'],3);
                if ($rows) {
                    $rows = $rows->toArray();
                    $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 3);
                    return $rows;
                }

            }elseif($art_category_id==2){  //市场动态管理
                $model = new Arttype();
                $where['id'] = 2;
                $rows = $model->ArttypewithArtList($where,'*',['id'=>'desc'],4);
                if ($rows) {
                    $rows = $rows->toArray();
                    $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 3);
                    return $rows;
                }

            }elseif($art_category_id==7){  //团队信息管理

                $model = new Arttype();
                $where['parent_id'] = 7;
                if(!empty($news_id)){
                    $where['id'] = $news_id;
                    //dd($news_id);
                }
                $rows = $model->ArttypewithArtList($where,'*',['id'=>'desc'],1);  //一个类别下面有许多文章
                if ($rows) {
                    $rows = $rows->toArray();
                    $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 3);

                }

                return $rows;

            }

                return '参数错误!';

        }else{
            return '参数错误';
        }

    }

    /**
     *
     *通过article_id获取一篇文章信息
     *
     */
    public function getOneArticle($request)
    {

        $article_id = isset($request['article_id'])?trim($request['article_id']):'';
        $data = $this->getOne(['article_id'=>$article_id])->toArray();
        return $data;
    }



    /**
     *
     * 添加文章
     */
    public function addArticle($request)
    {
        $data['title'] = isset($request['title'])?trim($request['title']):'';//标题
        $data['content'] = isset($request['content'])?trim(html_entity_decode($request['content'])):'';   //内容
        $data['position_id'] = isset($request['article_category_id'])?trim($request['article_category_id']):'';//类型  根据类型表的id 对比
        $data['sign'] = isset($request['sign'])?trim($request['sign']):'';//是否标红
        if(!isset($data['title'])||!isset($data['content'])||!isset($data['position_id'])||!isset($data['sign'])){
            $res = '表单不能为空';
            return $res;
        }
        $data['add_time'] = time();//添加时间

        $did = $this->add($data);
        if(!$did){
            $res = '服务器繁忙,请稍后重试';
            return $res;
        }
        $res = '添加文章成功';
        return $res;


    }

    /**
     *
     * 修改文章
     */
    public function saveArticle($request)
    {

        $data['title'] = isset($request['title'])?trim($request['title']):'';//标题
        $data['content'] = isset($request['content'])?trim(html_entity_decode($request['content'])):'';   //内容
        $data['position_id'] = isset($request['article_category_id'])?trim($request['article_category_id']):'';//类型  根据类型表的id 对比
        $data['sign'] = isset($request['sign'])?trim($request['sign']):'';//是否标红
        if(!isset($data['title'])||!isset($data['content'])||!isset($data['position_id'])||!isset($data['sign'])){
            $res = '表单不能为空';
            return $res;
        }
        $article_id = isset($request['article_id'])?trim($request['article_id']):'';//文章id
        if(!isset($article_id)){
            return '参数错误!';
        }

        $where['article_id'] = $article_id;
        $did = $this->up($where,$data);
        if(!$did){
            $res ="服务器繁忙,请稍后重试";
            return $res;
        }
        $res = "修改文章成功";
        return $res;


    }

    /**
     * 前台首页信息
     */

    //查询非标红文章（6个）
    public function info($id){
        $where['article_category.id'] = intval($id);
        $info = DB::table('article')
            ->join('article_category','article.position_id','=','article_category.id')
            ->where($where)
            ->where('article.sign', 0)
            ->orderBy('add_time','desc')
            ->get();///排序，规定固定10个，红4灰6，///排序，规定固定10个，红4灰6，
        if($info){
            return object_array($info);
        }else{
            return false;
        }
    }
    //查询标红文章（4个）
    public function info_red($id){
        $where['article_category.id'] = intval($id);
        $info = DB::table('article')
            ->join('article_category','article.position_id','=','article_category.id')
            ->where($where)
            ->where('article.sign',1)
            ->orderBy('add_time','desc')
            ->get();///排序，规定固定10个，红4灰6，///排序，规定固定10个，红4灰6，
        if($info){
            return object_array($info);
        }else{
            return false;
        }
    }

    public function info_one($id){
        $where['article_category.id'] = intval($id);
        $info = DB::table('article')
            ->join('article_category','article.position_id','=','article_category.id')
            ->where($where)
            ->orderBy('add_time','desc')
            ->get();///排序，规定固定10个，红4灰6，///排序，规定固定10个，红4灰6，
        if($info){
            return object_array($info);
        }else{
            return false;
        }
    }

    /***********前台***********/

    /**
     * 最新动态
     */
    public function index($request){
        //检测从哪里进来到这里，如果有参数，判断分类（position）1为系统，2为资源，没有参数，正常显示
        $id = intval($request['id']);//强制转换为数字型
        $random_id = intval($request['random_id']);
        $where = [];
        if(!$random_id){
            $where['position_id'] = ['in',[1,2]];
        }
        if(!empty($id)){//有参数，判断1，2，参数数量不确定
            $where['position_id'] = $id;
        }
        $pageSize = 5;
        $list =$this->getList($where,'*',['add_time'=>'desc'],$pageSize)->toArray();
        foreach ($list['data'] as $k=>$v){
            $list[$k]['title'] = strip_tags(html_entity_decode($v['title']));
            $list[$k]['content'] = strip_tags(html_entity_decode($v['content']));
        }
        $list['pageNoList'] = getPageNoList($list['last_page'], request('page', 1), 5);
       return $list;
    }

    /**
     * 页面左边为选中的信息，通过url传递的id获取，并获取到该文章的position_id，用position_id来确定右边的分类名和分类中需要的多个标题
     * return array 文章分类，分页，查询信息
     */
    public function details($requst){
//        $article = M('Article');
//        $art_cat = M('Article_category');
        //index 传id
        $id = $requst['article_id'];
        $team_id = $requst['team_id'];
        $where =[];
        if (!empty($id)) {
            $where['article_id'] = $id;
        }
        if (!empty($team_id)) {
            $where['article_id'] = $team_id;
        }

        $count = Art::where($where)->count();
        if($count==0){
            abort(404);
            return;
        }

        $art_one = Art::where($where)->first();//查找到单一的文章
        //将数据库中html标签字符串化，显示
        $art_one['title'] = html_entity_decode($art_one['title']);
        $art_one['content'] = html_entity_decode($art_one['content']);
        //根据单一文章的position_id,查找一定量的同类型标题

        $where_artlist['position_id'] = $art_one['position_id'];
        $art_list = Art::where($where_artlist)->orderBy('add_time','desc')->take(5)->get();
       return [$art_one,$art_list];
    }

}
